package slingge.cooleuropeweather;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;

import java.io.File;
import java.io.IOException;

public class Map extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private String str,str1,EmailNumber,PhoneNumber;
    private Uri uri = null;
    public int CO,SO2,O3,NO2,PM10,PM25;
    public String Qlty,AQI,Temper,Weather;
    public double latitude,longitude;
    private MapView mMapView = null;
    private BaiduMap mBaiduMap = null;
    //照片选择路径
    public  String mCurrentPhotoPath = null;
    //定位地址
    public String LocationName;
    //定位服务的客户端
    private LocationClient mLocationClient = null;
    //定位监听
    private  MyLocationListener myListener = new MyLocationListener();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_map);
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setIsNeedLocationDescribe(true);
        option.setScanSpan(10000);
        option.setNeedDeviceDirect(true);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.map, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        str = item.getTitle().toString();
        //noinspection SimplifiableIfStatement
        if (id == R.id.map_hotmap&&str.equals("热力地图")) {
            mBaiduMap.setBaiduHeatMapEnabled(true);
            item.setTitle("关闭热力");
        }
        if (id == R.id.map_hotmap&&str.equals("关闭热力")) {
            mBaiduMap.setBaiduHeatMapEnabled(false);
            item.setTitle("热力地图");
        }
        if (id == R.id.map_satelife&&str.equals("卫星地图") ){
            mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
            item.setTitle("普通地图");
        }
        if (id == R.id.map_satelife&&str.equals("普通地图") ){
            mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
            item.setTitle("卫星地图");
        }
        if (id == R.id.map_trafficmap&&str.equals("交通地图") ){
            mBaiduMap.setTrafficEnabled(true);
            item.setTitle("关闭交通");
        }
        if (id == R.id.map_trafficmap&&str.equals("关闭交通") ){
            mBaiduMap.setTrafficEnabled(false);
            item.setTitle("交通地图");
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_camera) {
            dispatchTakePictureIntent();
        } else if (id == R.id.nav_gallery) {
            Intent intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent,1);
        } else if (id == R.id.nav_slideshow) {
            Intent intent = new Intent();
            intent.setClass(Map.this,MainActivity.class);
            startActivityForResult(intent,2);
        } else if (id == R.id.nav_manage) {
            Intent intent = new Intent();
            intent.setClass(Map.this,Setting.class);
            startActivityForResult(intent,3);
        } else if (id == R.id.nav_share) {
            str1 = "大致位置："+ LocationName+"  当前温度："+Temper+"  天气状况："+Weather+"\n"+"AQI指数："+AQI+"  质量等级："+Qlty+
                    "  PM2.5："+PM25+"mg/m3"+"  PM10："+PM10+"mg/m3"+"  SO2："+SO2+"mg/m3"+"  CO："+CO+"mg/m3"+
                    "  O3："+O3+"mg/m3"+"  NO2："+NO2+"mg/m3";
            Intent emailIntent = new Intent(Intent.ACTION_SEND);
            emailIntent.setType("text/plain");
            emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,EmailNumber);
            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"环境监测");
            emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,str1);
            startActivity(Intent.createChooser(emailIntent,"Choose Email Client"));
        } else if (id == R.id.nav_send) {
            Intent i = new Intent(Map.this,Message.class);
            i.putExtra("location",LocationName);
            i.putExtra("latitude",latitude);
            i.putExtra("longitude",longitude);
            i.putExtra("Temper",Temper);
            i.putExtra("Weather",Weather);
            i.putExtra("AQI",AQI);
            i.putExtra("Qlty",Qlty);
            i.putExtra("PM2.5",PM25);
            i.putExtra("PM10",PM10);
            i.putExtra("SO2",SO2);
            i.putExtra("NO2",NO2);
            i.putExtra("CO",CO);
            i.putExtra("O3",O3);
            i.putExtra("PhoneNumber",PhoneNumber);
            startActivity(i);
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    //我的位置
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            LocationName=location.getLocationDescribe();
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            LatLng ll = new LatLng(location.getLatitude(),location.getLongitude());
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
            mBaiduMap.animateMapStatus(u);
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    }
    //以时间命名图片
    private File createImageFile() throws IOException {
        Long Ldate = System.currentTimeMillis();
        String name = Ldate.toString();
        File storageDir = new File("/sdcard/DCIM/Camera/");
        File image = File.createTempFile(name,".jpg", storageDir );
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        return image;
    }
    //启动相机，保存图片
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        getImageContentUri(photoFile));
                startActivityForResult(takePictureIntent,4);
            }
        }
    }
    //大气返回数据
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1){
            if(data!=null)
            uri = data.getData();
            else{
                return;
            }
        }
        else if(requestCode == 2) {
            AQI = data.getExtras().get("AQI").toString();
            Temper = data.getExtras().get("Temper").toString();
            Weather = data.getStringExtra("Weather");
            Qlty = data.getExtras().get("Qlty").toString();
            CO = data.getExtras().getInt("CO");
            SO2 = data.getExtras().getInt("SO2");
            NO2 = data.getExtras().getInt("NO2");
            O3 = data.getExtras().getInt("O3");
            PM10 = data.getExtras().getInt("PM10");
            PM25 = data.getExtras().getInt("PM2.5");
        }
        else if(requestCode == 3){
            PhoneNumber = data.getStringExtra("PhoneNumber");
            EmailNumber = data.getStringExtra("EmailNumber");
        }
       else if(resultCode == 4){

        }
        else{
            return;
        }
    }
    //Android7.0,将Uri转换为content
    public Uri getImageContentUri(File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID },
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }
}

